package com.classic.okhttp.crypt;

import android.util.Base64;

import com.classic.okhttp.defer.CoreDeferObject;
import com.classic.okhttp.defer.impl.DeferSecret;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;


/**
 * @author Rockey
 * @Description 加密只能在httppacket里调用，其他地方应该撤销
 */
public class AES implements DeferSecret {

    // 加密
    @Deprecated
    public  String encrypt(String sSrc, String sKey) throws Exception {

        byte[] raw = sKey.getBytes("utf-8");
        SecretKeySpec skeySpec =
                new SecretKeySpec(raw, "AES");
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");//"算法/模式/补码方式"
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec,new IvParameterSpec(Constants.iv.getBytes()));
        byte[] encrypted = cipher.doFinal(sSrc.getBytes("utf-8"));

        return  Base64.encodeToString(encrypted,Base64.NO_WRAP);

    }

    // 解密
    @Deprecated
    public  String decrypt(String sSrc, String sKey) throws Exception {
        try {

            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec,new IvParameterSpec(Constants.iv.getBytes()));
            byte[] encrypted1 = CoreDeferObject.get().getDeferBase64().base64Decode(sSrc);
            try {
                byte[] original = cipher.doFinal(encrypted1);
                String originalString = new String(original,"utf-8");
                return originalString;
            } catch (Exception e) {

                return null;
            }
        } catch (Exception ex) {

            return null;
        }
    }

    public  void main(String[] args) throws Exception {
        /*
         * 此处使用AES-128-ECB加密模式，key需要为16位。
         */
        String cKey = "7L26ZYCYRNQF43A3";
        // 需要加密的字串
        String cSrc = "123456";
        System.out.println(cSrc);
        // 加密
       AES aes=  new AES();
        String enString = aes.encrypt(cSrc, cKey);
        System.out.println("加密后的字串是：" + enString);

        // 解密
        String DeString = aes.decrypt("yJCb6ITCOfHunFDGNULIXA==", cKey);
        System.out.println("解密后的字串是：" + DeString);
    }
    @Deprecated
    @Override
    public String encrypt(String content) throws Exception {
        return encrypt(content, Constants.aeskey);
    }
    @Deprecated
    @Override
    public String decrypt(String content) throws Exception {
        return decrypt(content, Constants.aeskey);
    }
}
